package com.xsystem.api;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.context.ApplicationContext;

import com.xsystem.api.exception.ActionNotSupportedException;

public class PublicController extends XController {

	@Override
	protected String getDomain() {
		return "public";
	}

	@Override
	protected String getBeanName() {
		return "publicController";
	}

	@Override
	public String doAction(HttpServletRequest request,
			ApplicationContext context) {
		
		Map<String, Object> outputMap = new HashMap<String, Object>();
		String uri = request.getRequestURI();
		ResponseType responseFormat = this.getResponseFormat(uri);
		String action = getActionCode(uri);
		Map<String, String> params = new HashMap<String, String>();
		try {
			if (ServletFileUpload.isMultipartContent(request)) {
				params = getMultiPartContent(request);
			}
			params.putAll(getParameters(request));

			// String userIpAddress = params.get(Api.IN_IPADDRESS);
			String serverIpAddress = getRequestIp(request);

			params.put("action", action);
			params.put("serverIpAddress", serverIpAddress);

			apiMonitor.setInputParams(params);

			outputMap.putAll(executeAction(params, action, context));
		} catch (ActionNotSupportedException e) {
			outputMap.putAll(prepareErrorResponse(ERROR_ACTION_NOT_SUPPORTED,
					null));
		}

		String formattedResponse = this.formatResponse(outputMap,
				responseFormat);

		return formattedResponse;
	}

}
